package xyz.xuminghai.javafx_learn.scene.chart;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * 2023/5/29 14:24 星期一<br/>
 * 饼状图
 *
 * @author xuMingHai
 */
public class PieChartApp extends Application {

    private final ObservableList<PieChart.Data> observableList = FXCollections
            .observableArrayList(new PieChart.Data("data1", 25.0),
                    new PieChart.Data("data2", 23.0),
                    new PieChart.Data("data3", 33.0),
                    new PieChart.Data("data4", 41.0),
                    new PieChart.Data("data5", 32.0),
                    new PieChart.Data("data6", 18.0));
    private final PieChart pieChart = new PieChart(observableList);

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void init() {
        ScheduledService<Void> scheduledService = new ScheduledService<>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<>() {
                    @Override
                    protected Void call() {
                        PieChart.Data data = observableList.get((int) (Math.random() * observableList.size()));
                        int i = (int) (Math.random() * 2);
                        int value = (int) (Math.random() * 10);
                        value = (i == 0) ? value : -value;
                        data.setPieValue(data.getPieValue() + value);
                        return null;
                    }
                };
            }
        };

        scheduledService.setPeriod(Duration.seconds(1.0));
        scheduledService.start();
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle(getClass().getSimpleName());
        Scene scene = new Scene(pieChart, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}
